package com.example.newbiechen.ireader.service.boluoxs;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;

import com.example.newbiechen.ireader.App;
import com.example.newbiechen.ireader.model.bean.BookChapterBean;
import com.example.newbiechen.ireader.model.bean.ChapterInfoBean;
import com.example.newbiechen.ireader.model.bean.CollBookBean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleObserver;
import io.reactivex.SingleOnSubscribe;
import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by robrk on 2019/3/17.
 */

public final class BookService {
    public static CollBookBean getByUrlAsync(String url) throws IOException {
        String html = getHtml(url);
        CollBookBean collBookBean = HtmlHelper.getBookDetail(html);
        return collBookBean;
    }

    public static String getBookArticle(String urlPath) throws IOException {
        String url = "https://m.boluoxs.com" + urlPath;
        String html = getHtml(url);
        String str = HtmlHelper.getArticleText(html);
        StringBuffer content = new StringBuffer();
//        System.out.println(str);

        if(str.contains("    本章未完，点击下一页继续阅读》》")){
            str = str.replace("\n\n    本章未完，点击下一页继续阅读》》\n", "");
            content.append(str);
            // 获取下一页
            Pattern aPattern = Pattern.compile("<a class=\"dise\" href=\"([^\"]*?)\">下一章</a>");
            Matcher m = aPattern.matcher(html);
            if (m.find()){
//                System.out.println(m.group());
                String nextUrl = m.group(1);
                System.out.println("url:" + nextUrl);
                String nextContent = getBookArticle(nextUrl);
                return content.append(nextContent).toString();
            }
        }
        // 已获取完
        return str;
    }

    public static Single<ChapterInfoBean> getChapterInfo(String urlPath){
        return Single.create(new SingleOnSubscribe<ChapterInfoBean>() {
            @Override
            public void subscribe(SingleEmitter<ChapterInfoBean> e) throws Exception {
                ChapterInfoBean bean = new ChapterInfoBean();
                try {
                    bean.setBody(BookService.getBookArticle(urlPath));
                    if(bean.getBody().equals("")){
                        throw new Exception("文章下载失败： " + urlPath);
                    }
                    e.onSuccess(bean);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        });
    }

    public static Single<List<BookChapterBean>> getChaptersSingle(String url, String bookId){
//        Single.create(new Single.OnSubscribe<Integer>() {
//            @Override
//            public void call(SingleSubscriber<? super Integer> singleSubscriber) {
//                // 这里被指定在IO线程
//                singleSubscriber.onSuccess(addValue(1, 2));
//            }
//        })

        return Single.create(new SingleOnSubscribe<List<BookChapterBean>>() {
            @Override
            public void subscribe(SingleEmitter<List<BookChapterBean>> e) throws Exception {
                e.onSuccess(BookService.getChapters(url, bookId));
            }
        });
//        return new Single<List<BookChapterBean>>() {
//            @Override
//            protected void subscribeActual(SingleObserver<? super List<BookChapterBean>> observer) {
//
//            }
//        };

    }

    public static List<BookChapterBean> getChapters(String url, String bookId) throws Exception {
        SharedPreferences sharedPreferences = App.getContext().getSharedPreferences("ChapterLock", Context.MODE_PRIVATE);
        //步骤2-1：创建一个SharedPreferences.Editor接口对象，lock表示要写入的XML文件名，MODE_WORLD_WRITEABLE写操作
        SharedPreferences.Editor editor = sharedPreferences.edit();


        List<BookChapterBean> bookChapterBeans = new ArrayList<>();

        String lastUrl = sharedPreferences.getString(bookId, null);

        if(lastUrl== null){
            lastUrl = url;
        }
//        if(lastUrl != null){
//            String html = getChapterHtml(url);
//
//
//        }else {
            String html = getChapterHtml(lastUrl);
            List<String> menuGroup = null;

            if(menuGroup == null){
                List<String> lstMenuGroup =HtmlHelper.getMenuGroup(html);
                List<String> lstNew = new ArrayList<>();
                for (String item : lstMenuGroup){
                    if(item.compareTo(lastUrl) > 0){
                        lstNew.add(item);
                    }
                }
                menuGroup = lstNew;

//                // 只更新最后一个分组
//            if(lstMenuGroup.size()>0){
//                List<String> lstNew = new ArrayList<>();
//                lstNew.add(lstMenuGroup.get(0));
//
////                lstMenuGroup.subList()
//                lstNew.add(lstMenuGroup.get(lstMenuGroup.size()-1));
//                menuGroup = lstNew;
//            }

                // 更新所有
//                menuGroup = lstMenuGroup;
            }


//            //步骤2-2：将获取过来的值放入文件
//            editor.putString("code", "");
//            //步骤3：提交
//            editor.commit();


            bookChapterBeans.addAll(HtmlHelper.getMenus(html));
            //
            if(menuGroup != null){
                int i = 0;
                for (String menu : menuGroup){
                    i ++ ;
                    if(i<menuGroup.size()-2){
                        continue;
                    }
//                    Thread.sleep(1000);
                    System.out.println(menu);
                    try {
                        html = getChapterHtml(menu);
                        bookChapterBeans.addAll(HtmlHelper.getMenus(html));
                    }catch (Exception ex){
                        ex.printStackTrace();
                        cookieStore.clear();
                        Thread.sleep(10000);
                        html = getChapterHtml(menu);
                        bookChapterBeans.addAll(HtmlHelper.getMenus(html));
                    }

                    //步骤2-2：将获取过来的值放入文件
                    editor.putString(bookId, menu);
                }

                //步骤3：提交
                editor.commit();
            }
//        }

        if(bookChapterBeans.size() == 0){
            throw new Exception("获取目录失败");
        }

        return bookChapterBeans;
    }

    public static List<BookChapterBean> getChapters2(String url, String lastUrl) throws Exception {

        List<BookChapterBean> bookChapterBeans = new ArrayList<>();

        if(lastUrl== null){
            lastUrl = url;
        }

        String html = getChapterHtml(lastUrl);
        List<String> menuGroup = null;

        if(menuGroup == null){
            List<String> lstMenuGroup =HtmlHelper.getMenuGroup(html);
            boolean beginAdd = false;
            List<String> lstNew = new ArrayList<>();
            for (String item : lstMenuGroup){
                if(item.compareTo(lastUrl) > 0){
                    lstNew.add(item);
                }else {
//                    if(beginAdd){
//                        lstNew.add(item);
//                    }else {
//                        if(item.equals(lastUrl) || url.equals(lastUrl)){
//                            beginAdd = true;
//                        }
//                    }
                }

            }
            menuGroup = lstNew;

        }

        bookChapterBeans.addAll(HtmlHelper.getMenus(html));
        //
        if(menuGroup != null){
            for (String menu : menuGroup){
                html = getChapterHtml(menu);
                bookChapterBeans.addAll(HtmlHelper.getMenus(html));
            }
        }

        return bookChapterBeans;
    }

    public static String getChapterHtml(String urlPath) throws IOException {
        String url = "https://m.boluoxs.com" + urlPath;
        return getHtml(url);
    }

    private static final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

    public static String getHtml(String url) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {
                    @Override
                    public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
                        cookieStore.put(httpUrl.host(), list);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl httpUrl) {
                        List<Cookie> cookies = cookieStore.get(httpUrl.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

//        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501 NetType/WIFI WindowsWechat QBCore/3.43.1021.400 QQBrowser/9.0.2524.400")
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        Response response = call.execute();
//        Log.d("BookDetailService", "run: " + response.body().string());
        byte[] b = response.body().bytes(); //获取数据的bytes
        String html = new String(b, "GBK"); //然后将其转为gbk
        return html;
    }
}
